/*
 * Copyright 2011 The Rusted Roof, LLC.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package org.proteusframework.platformservice.messaging.basic;

import org.proteusframework.core.api.IProteusConstants;
import org.proteusframework.core.api.model.INamespace;
import org.proteusframework.core.base.Namespace;
import org.proteusframework.platformservice.messaging.AbstractMessageService;
import org.proteusframework.platformservice.messaging.IMessageBean;
import org.proteusframework.platformservice.messaging.IMessageService;
import org.proteusframework.platformservice.messaging.IMessageSink;

import java.util.Properties;
import java.util.logging.Logger;

/**
 * Thread-safe message service built around Java's <code>BlockingQueue</code>.
 */
public class DefaultMessageService extends AbstractMessageService
{
    static final INamespace NS = new Namespace(IProteusConstants.NAMESPACE, "DefaultMessageService");

    private static final Logger logger = Logger.getLogger(DefaultMessageService.class.getCanonicalName());

    public DefaultMessageService()
    {
        super(NS);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void start()
    {
        logger.config("DefaultMessageService has started");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void stop()
    {
        logger.config("DefaultMessageService has stopped");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public <T extends IMessageBean> IMessageSink<T> requestMessageSink(INamespace namespace, Class<T> messageBeanClass, Properties metadata)
    {
        synchronized (lock)
        {
            if (!sinkExists(namespace))
            {
                //
                // Create a new instance of a message sink under the given namespace, associated with the specific
                // message bean class

                int maxCapacity = 50;

                String requestedMax = metadata.getProperty(IMessageService.KEY_MAXIMUM_CAPACITY);
                if (null != requestedMax)
                {
                    try
                    {
                        maxCapacity = Integer.parseInt(requestedMax);
                    } catch (NumberFormatException e)
                    {
                        logger.warning("KEY_MAXIMUM_CAPACITY value in metadata could not be converted to an integer: "
                                + requestedMax + ": " + e.getMessage());
                    }
                }

                logger.config("Creating instance of IMessageSink under namespace " + namespace
                        + " for message bean class " + messageBeanClass.getCanonicalName()
                        + " with max capacity of " + maxCapacity);

                BlockingQueueMessageSink<T> sink
                        = new BlockingQueueMessageSink<T>(namespace, messageBeanClass, metadata, maxCapacity);

                putSink(namespace, sink);
            }
        }


        IMessageSink<T> messageSink = getSink(namespace);
        if (messageSink.getMessageBeanClass() != messageBeanClass)
        {
            logger.severe("IMessageSink message bean class mismatch: {Actual: "
                    + messageSink.getMessageBeanClass().getCanonicalName()
                    + "}, {Requested: " + messageBeanClass.getCanonicalName());

            throw new IllegalArgumentException("Mismatch between actual message bean class and requested message bean class for the message sink at " + namespace);
        }


        return messageSink;
    }
}
